package com.supreme.securityserver.security;

import com.alibaba.fastjson.JSON;
import com.supreme.commonboot.utils.AjaxResp;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        System.out.println("authException.getMessage() = " + authException.getMessage());
        String msg = String.format("请求访问: %s，认证失败，无法访问系统资源", request.getRequestURI());

        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(JSON.toJSONString(AjaxResp.instance(HttpStatus.UNAUTHORIZED.value(), msg)));
    }
}
